package com.fadadianqi.logistics.admin.printer;

import com.fadadianqi.commons.ConfigHelper;
import com.fadadianqi.commons.VelocityWrapper;
import com.fadadianqi.goods.model.Brand;
import com.fadadianqi.goods.model.Category;
import com.fadadianqi.goods.model.Goods;
import com.fadadianqi.goods.service.GoodsService;
import com.fadadianqi.logistics.inventory.model.Backtrack;
import com.fadadianqi.logistics.inventory.model.BacktrackBatch;
import com.fadadianqi.logistics.inventory.model.Batch;
import com.fadadianqi.logistics.inventory.service.BacktrackService;
import com.fadadianqi.logistics.inventory.service.InventoryService;
import com.yeqiangwei.commons.util.BeanUtils;
import com.yeqiangwei.commons.util.DateTimeUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.print.Paper;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

@Service
public class BacktrackPrinter {

    private static final Logger log = Logger.getLogger(BacktrackPrinter.class);

    public void doPrint(String backtrackId) throws Exception {
        int offsetX = ConfigHelper.getInt("vm.printer.offsetX", 10);
        int offsetY = ConfigHelper.getInt("vm.printer.offsetY", 10);
        int width = ConfigHelper.getInt("vm.printer.width", 585);
        int height = ConfigHelper.getInt("vm.printer.height", 800);
        Paper p = new Paper();
        p.setSize(width, height); // 纸张大小
        p.setImageableArea(offsetX, offsetY, width, height);
        PrintService printService = new PrintService(getContent(backtrackId), p);
        printService.doPrint();
    }

    private void contextWapper(VelocityContext context, String backtrackId) {
        Backtrack b = backtrackService.getBacktrackById(backtrackId);
        // 这个是用来判断是否打印商品单价
        context.put("title", ConfigHelper.getString("printer.title"));
        context.put("address", ConfigHelper.getString("printer.address"));
        context.put("tel", ConfigHelper.getString("printer.tel"));
        context.put("datetime", DateTimeUtils.format(b.getAddTime().getTime(), DateTimeUtils.FMT_YYYY_MM_DD_HH_MM_SS));
        context.put("ident", b.getId());
        context.put("money", b.getMoney());
        context.put("memo", b.getMemo());
        List<BacktrackBatch> items = backtrackService.findBatchByBacktrackId(backtrackId);
        List<GoodsVO> voList = new ArrayList<GoodsVO>();
        if (items == null) {
            return;
        }
        for (BacktrackBatch bb : items) {
            GoodsVO vo = new GoodsVO();
            Goods goods = goodsService.getGoodsById(bb.getGoodsId());
            BeanUtils.copyProperties(vo, goods);
            vo.setGoods(goodsService.getGoodsById(bb.getGoodsId()));
            vo.setBrand(goodsService.getBrandById(bb.getBrandId()));
            vo.setCategory(goodsService.getCategoryById(bb.getCategoryId()));
            vo.setCount(bb.getCount());

            Batch batch = inventoryService.getBatchById(bb.getBatchId());
            vo.setPrice(batch.getCost());
            voList.add(vo);
        }
        context.put("items", voList);
    }

    private String getContent(String backtrackId) {
        String baseDir = System.getProperty("base.dir", "..");
        String path = baseDir + "printer" + File.separator;
        VelocityEngine ve = VelocityWrapper.getVelocityInstance();
        String templatePath = ConfigHelper.getString("vm.printer.template.path", path);
        String templateName = ConfigHelper.getString("vm.printer.template.backtrack.name");
        log.debug("templatePath: " + templatePath);
        log.debug("templateName: " + templateName);
        ve.setProperty("file.resource.loader.path", templatePath);
        Template t = VelocityWrapper.getTemplate(ve, templateName);
        VelocityContext context = new VelocityContext();
        contextWapper(context, backtrackId);
        StringWriter writer = new StringWriter();
        try {
            t.merge(context, writer);
        } catch (ResourceNotFoundException e) {
            log.error(e.toString());
        } catch (ParseErrorException e) {
            log.error(e.toString());
        } catch (MethodInvocationException e) {
            log.error(e.toString());
        } catch (IOException e) {
            log.error(e.toString());
        }
        return writer.toString();
    }

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private BacktrackService backtrackService;

    @Autowired
    private GoodsService goodsService;

    public static class GoodsVO implements java.io.Serializable {

        /**
         *
         */
        private static final long serialVersionUID = -3501688200769307039L;
        private Goods goods;
        private Brand brand;
        private Category category;
        private int count;
        private double price;

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public double getPrice() {
            return price;
        }

        public void setPrice(double price) {
            this.price = price;
        }

        public Goods getGoods() {
            return goods;
        }

        public void setGoods(Goods goods) {
            this.goods = goods;
        }

        public Brand getBrand() {
            return brand;
        }

        public void setBrand(Brand brand) {
            this.brand = brand;
        }

        public Category getCategory() {
            return category;
        }

        public void setCategory(Category category) {
            this.category = category;
        }
    }
}
